package com.sandbox.search;

import org.apache.commons.cli.*;
import org.apache.lucene.search.highlight.InvalidTokenOffsetsException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class SearchConsole {
    public static void main(String[] args) throws IOException, ParseException,
            org.apache.lucene.queryParser.ParseException, InvalidTokenOffsetsException {
        Options options = new Options();
        options.addOption("i", true, "index directory (full path)");
        CommandLineParser parser = new PosixParser();
        CommandLine cmd = parser.parse(options, args);
        String inputDir = cmd.getOptionValue("i");

        BufferedReader commandInputReader = new BufferedReader(new InputStreamReader(System.in));
        String line;
        System.out.print("> ");
        DataSearcher searcher = new DataSearcher(inputDir);

        while (!"exit".equals(line = commandInputReader.readLine())) {
            SearchResponse searchResponse = searcher.search(line, 0, 2, 100, "+++", "+++");
            System.out.println(String.format("--- results[total:%d, offset:%d, pageSize:%d] ---",
                    searchResponse.getMaxResults(), searchResponse.getOffset(), searchResponse.getPageSize()));
            for (SearchResult searchResult : searchResponse.getResults()) {
                System.out.println(String.format("%.2f: %s: %s", searchResult.getScore(), searchResult.getFilename(),
                        searchResult.getHighlightedFragment()));
            }
            System.out.print("> ");
        }
    }
}
